package com.liuhongwei.test.entity.vo;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 */
public class JSONRequest<T> extends JSONCommon {

    protected String client;

    protected String version;

    protected String data;

    protected  String traceId;

    private String zone;

    private String lang;


    public JSONRequest() {
    }

    protected void setUser(String user) {
        put("user",user);
    }

    protected void setKey(String key) {
        put("key",key);
    }

    protected void setClient(String client) {
        put("client",client);
    }

    protected void setVersion(String version) {
        put("version",version);
    }

    protected void setData(String data) {
        put("data",data);
    }

    @Override
    public String getUser() {
        return (String) super.get("user");
    }

    @Override
    public String getKey() {
        return (String) super.get("key");
    }

    public String getVersion() {
        return (String) super.get("version");
    }

    public String getTraceId() {
        return traceId;
    }

    public void setTraceId(String traceId) {
        this.traceId = traceId;
        put("traceId", traceId);
    }

    public String getZone() {
        return getDefaultValue(super.getString("zone"),"8");
    }

    public void setZone(String zone) {
        put("zone",zone);
    }

    public String getLang() {
        return  getDefaultValue(super.getString("lang"),"ZH");
    }

    public void setLang(String lang) {
        put("lang",lang);
    }

    public RequestClient getClient() {
        return RequestClient.valueOf((String) super.get("client"));
    }

    public T getData() {
        return (T) super.get("data");
    }

    public JSONObject getJsonObjectData() {
        Object ob = super.get("data");
        if (ob != null) {
            if (ob instanceof String) {
                String fix = (String) ob;
                return JSONObject.parseObject(fix.replaceAll("\r\n\t", ""));
            }
            String jstr = JSONObject.toJSONString(ob);
            return JSONObject.parseObject(jstr);
        } else {
            return new JSONObject();
        }
    }

    public static void main(String[] args) {
        JSONRequest re = new JSONRequest();
        re.setKey("a");
        re.setUser("b");
        System.out.println(re);

        Object orDefault = re.getOrDefault("lang", "ZH");
        System.out.println(orDefault);
    }


    private String getDefaultValue(String param,String defaultValue){
        if(StringUtils.isEmpty(param)){
            return defaultValue;
        }
        return param;
    }
}